package com.mercury.pattern._11_proxy._002_jdk_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {

    ITeacherDao teacherDao;

    public ProxyFactory(ITeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }

    public Object getProxyInstance(){
        /**
         * classLoader: 类加载器
         * interfaces:目标类的接口
         * InvocationHandler: 调用目标对象时会回调
         */
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                new Class[]{ITeacherDao.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理前..");
                        Object val = method.invoke(teacherDao,args); //调用目标方法
                        return val;
                    }
                });
    }
}
